const koa = require('koa')
const jwt = require('koa-jwt')
const jwttoken = require('jsonwebtoken')
const config = require('./config/index')


const app = new koa()


app.use(async (ctx, next) => {
  // 再这里先做权限认证, 然后在 next()
  if(ctx.headers && ctx.headers.authorization){
    const token = ctx.headers.authorization
    let payload = jwttoken.verify(token, config.secret) // 解密, 获取payload
    if (payload.data === 'admin') {
      next()
    } else {
      ctx.status = 401
      ctx.body = 'use headers to get access'
    }
    ctx.body = 'asdasd'
  } else {
    await next().catch(error => {
      if (error.status === 401) {
        ctx.status = 401
        ctx.body = 'use headers to get access'
      } else {
        ctx.status = error.status
        ctx.body = ctx.message
      }
    })
  }
})


const router = require('./routes/index')
app.use(router.routes(), router.allowedMethods())

app.use(
  jwt({ secret: config.secret, passthrough: true }).unless({
    path: ['/register', '/login']
  })
)

app.listen(3000, () => {
  console.log('server is running at port 3000')
})